﻿using CPPEI.WebApi;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CMS.WebApi.Media
{
    [AuthPostAction("media", "upload", "1.0")]
    public class UploadAction : BaseAction<UploadParams, UploadResult>
    {
        protected override ActionResult<UploadResult> OnExecute(ActionContext context, SysParams sysParams, UploadParams opParams)
        {
            Guid id = Guid.NewGuid();
            string extension = GetExtension(opParams.File.FileName);
            string relativeFilePath = string.Format("~/_temp/{0}.{1}", id.ToString(), extension);
            string tempFilePath = HttpContext.Current.Server.MapPath(relativeFilePath);

            try
            {
                FileInfo fileInfo = new FileInfo(tempFilePath);
                if(fileInfo.Directory.Exists == false)
                {
                    fileInfo.Directory.Create();
                }

                opParams.File.SaveAs(tempFilePath);
                UploadResult actResult = new UploadResult();
                actResult.Id = id;
                actResult.RelativeFilePath = relativeFilePath;
                return new ActionResult<UploadResult>(actResult);
            }
            catch(Exception ex)
            {
                return new ActionResult<UploadResult>(new CPPEI.ServiceResult(0, ex.Message));
            }
        }

        private string GetExtension(string fileName)
        {
            string[] fileSegments = fileName.Split(new char[]{'.'}, StringSplitOptions.RemoveEmptyEntries);
            if(fileSegments.Length == 0)
            {
                return string.Empty;
            }
            return fileSegments.Last();
        }
    }

    public class UploadParams
    {
        public System.Web.HttpPostedFile File { get; set;}
    }

    public class UploadResult
    {
        public Guid Id { get; set; }

        public string RelativeFilePath { get; set; }
    }
}
